var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var md5 = require('md5');
var responseData;
var config = require('../config/config.js');
var db = mysql.createPool({ host: config.host, user: config.user, password: config.password, database: config. database})


router.use(function(req, res, next) {
    responseData = {
        code: 0,
        message: ''
    }
    next()
})

router.get('/', function(req, res, next) {
    res.render('admin/reg');
})

// 用户注册
router.post('/', function(req, res, next) {
    var username = req.body.username;
    var password = req.body.password;
    var mpassword = req.body.mpassword;
    // console.log(username, password, mpassword);

    if (username == '') {
        responseData.code = -1;
        responseData.message = '用户名不能为空';
        res.json(responseData);
        return;
    }
    if (password == '' || mpassword == '') {
        responseData.code = -2;
        responseData.message = '密码不能为空';
        res.json(responseData);
        return;
    }
    if (password != mpassword) {
        responseData.code = -3;
        responseData.message = '两次输入的密码不相等';
        res.json(responseData);
        return;
    }

    password = md5(password);

    // 查询用户名是否存在
    db.query(`SELECT *FROM  zq_user WHERE username ='${username}'`, function(err, data) {
        if (err) {
            responseData.code = -4;
            responseData.message = '数据库睡着啦';
            res.json(responseData);
            console.log(err)
            return;
        } else {
            if (data.length) {
                responseData.code = -5;
                responseData.message = '该用户名已经存在啦';
                res.json(responseData);
                return;
            } else {

                // 新增用户
                db.query(`INSERT INTO zq_user(username,password) VALUES ( '${username}','${password}')`, function(err, data) {
                    if (err) {
                        responseData.code = -6;
                        responseData.message = '数据库睡着啦';
                        res.json(responseData);
                        console.log(err)
                        return;
                    } else {
                        responseData.message = '注册成功，赶快去登录吧';
                        res.json(responseData);
                        // res.render('admin/login');
                    }

                })
            }
        }
    })

})


module.exports = router